#include "DockingTabWell.h"
#include "DockTab.h"
#include "DockingTabStack.h"
#include <QPainter>
#include <QMouseEvent>
#include <QContextMenuEvent>
#include <QDragEnterEvent>
#include <QMimeData>
#include <QApplication>
#include <QMenu>
#include <QDebug>
#include <cassert>

// 静态常量定义
const int TAB_HEIGHT = 30;
const int MIN_TAB_WIDTH = 80;
const int MAX_TAB_WIDTH = 160;

DockingTabWell::DockingTabWell(QWidget* parent)
    : QFrame(parent)
    , m_parentStack(nullptr)
    , m_foregroundIndex(-1)
    , m_maxTabSize(MAX_TAB_WIDTH, TAB_HEIGHT)
    , m_needsLayout(true)
    , m_draggedTab(nullptr)
    , m_dropIndicatorIndex(-1)
    , m_previewFromIndex(-1)
    , m_previewToIndex(-1)
{
    setupTabWell();
}

DockingTabWell::DockingTabWell(DockingTabStack* parentStack, QWidget* parent)
    : QFrame(parent)
    , m_parentStack(parentStack)
    , m_foregroundIndex(-1)
    , m_maxTabSize(MAX_TAB_WIDTH, TAB_HEIGHT)
    , m_needsLayout(true)
    , m_draggedTab(nullptr)
    , m_dropIndicatorIndex(-1)
    , m_previewFromIndex(-1)
    , m_previewToIndex(-1)
    , m_showPreview(false)
{
    setupTabWell();
}

DockingTabWell::~DockingTabWell()
{
    clear();
}

void DockingTabWell::setupTabWell()
{
    // 基础设置
    setFrameStyle(QFrame::NoFrame);
    setLineWidth(0);
    setContentsMargins(0, 0, 0, 0);
    
    // 设置固定高度
    setFixedHeight(TAB_HEIGHT);
    setMinimumWidth(MIN_TAB_WIDTH);
    
    // 支持拖放
    setAcceptDrops(true);
    
    // 悬停跟踪
    setAttribute(Qt::WA_Hover, true);
    
    // 样式通过外部QSS文件控制，不在这里硬编码
    // setStyleSheet() - 已移除硬编码样式，使用dark_theme.qss
}

// === 标签页管理 ===

void DockingTabWell::addTab(DockTab* tab, int index, bool keepInactive)
{
    // 断言：标签不应该为空
    assert(tab != nullptr && "Tab cannot be null");
    // 断言：标签不应该已经存在
    assert(!m_tabs.contains(tab) && "Tab should not already exist in this well");
    
    if (!tab || m_tabs.contains(tab)) return;
    
    // 设置父容器
    tab->setParent(this);
    
    // 插入到指定位置
    if (index < 0 || index >= m_tabs.size()) {
        m_tabs.append(tab);
        index = m_tabs.size() - 1;
    } else {
        m_tabs.insert(index, tab);
        
        // 调整foreground索引
        if (m_foregroundIndex >= index) {
            m_foregroundIndex++;
        }
    }
    
    // 连接信号
    connectTabSignals(tab);
    
    // 设置标签类型（如果没有主标签且这是第一个标签，则设为主标签）
    if (!hasMainTab() && m_tabs.size() == 1) {
        tab->setTabType(DockTab::TabType::MainTab);
    }
    
    // 激活标签页
    if (!keepInactive) {
        bringTabToFront(index);
    }
    
    // 更新布局
    m_needsLayout = true;
    arrangeChildren();
    
    emit tabAdded(tab, index);
}

void DockingTabWell::removeTab(DockTab* tab) {
    int index = getTabIndex(tab);
    if (index >= 0) {
        removeTab(index);
    }
}

void DockingTabWell::removeTab(int index) {
    // 断言：索引应该有效
    assert(index >= 0 && index < m_tabs.size() && "Tab index out of range");
    
    if (index < 0 || index >= m_tabs.size()) return;
    
    // 不允许删除主标签（无论在什么位置）
    DockTab* tabToRemove = m_tabs.at(index);
    // 断言：要删除的标签不应该为空
    assert(tabToRemove != nullptr && "Tab to remove cannot be null");
    
    if (tabToRemove->tabType() == DockTab::TabType::MainTab) {
        qWarning() << "Cannot remove main tab";
        return;
    }
    
    DockTab* tab = m_tabs.takeAt(index);
    
    // 断开信号连接
    disconnectTabSignals(tab);
    
    // 调整foreground索引
    if (m_foregroundIndex == index) {
        m_foregroundIndex = -1;
        // 根据需求：标签出队后激活最右边标签
        if (!m_tabs.isEmpty()) {
            int newIndex = m_tabs.size() - 1; // 激活最右边标签
            bringTabToFront(newIndex);
        }
    } else if (m_foregroundIndex > index) {
        m_foregroundIndex--;
    }
    
    // 清理拖拽状态
    if (m_draggedTab == tab) {
        clearDraggedTab();
    }
    
    // 移除父容器
    tab->setParent(nullptr);
    
    // 更新布局
    m_needsLayout = true;
    arrangeChildren();
    
    emit tabRemoved(tab, index);
}

void DockingTabWell::clear() {
    while (!m_tabs.isEmpty()) {
        removeTab(m_tabs.size() - 1);
    }
    m_foregroundIndex = -1;
}

// === 激活状态管理 ===

void DockingTabWell::bringTabToFront(int index) {
    if (index < 0 || index >= m_tabs.size() || index == m_foregroundIndex) {
        return;
    }
    
    // 取消之前的激活状态
    if (m_foregroundIndex >= 0 && m_foregroundIndex < m_tabs.size()) {
        m_tabs[m_foregroundIndex]->setActiveTab(false);
    }
    
    // 设置新的激活状态
    m_foregroundIndex = index;
    m_tabs[index]->setActiveTab(true);
    
    // 更新布局（激活的标签可能需要不同的视觉效果）
    arrangeChildren();
    update();
    
    emit tabActivated(m_tabs[index], index);
}

void DockingTabWell::bringTabToFront(DockTab* tab) {
    int index = getTabIndex(tab);
    if (index >= 0) {
        bringTabToFront(index);
    }
}

DockTab* DockingTabWell::foregroundTab() const {
    if (m_foregroundIndex >= 0 && m_foregroundIndex < m_tabs.size()) {
        return m_tabs[m_foregroundIndex];
    }
    return nullptr;
}

int DockingTabWell::foregroundTabIndex() const {
    return m_foregroundIndex;
}

// === 标签页查询 ===

DockTab* DockingTabWell::tabAt(int index) const {
    if (index >= 0 && index < m_tabs.size()) {
        return m_tabs[index];
    }
    return nullptr;
}

int DockingTabWell::getTabIndex(DockTab* tab) const {
    return m_tabs.indexOf(tab);
}

// === 拖拽支持 ===

int DockingTabWell::calculateDropIndexForPosition(const QPoint& position, DockTab* draggedTab) {
    if (m_tabs.isEmpty()) return 0;
    
    // 计算标签宽度
    QSize tabSize = computeTabSize();
    int tabWidth = tabSize.width() - OVERLAP_WIDTH;
    
    // 基于X坐标计算索引，实现吸附逻辑
    int x = position.x();
    int draggedIndex = getTabIndex(draggedTab);
    
    // 遍历所有标签，找到应该插入的位置
    for (int i = 0; i < m_tabs.size(); ++i) {
        if (i == draggedIndex) continue; // 跳过被拖拽的标签本身
        
        int tabLeft = i * tabWidth;
        int tabRight = tabLeft + tabWidth;
        int tabCenter = (tabLeft + tabRight) / 2;
        
        // 根据鼠标位置决定吸附到标签的左侧还是右侧
        if (x >= tabLeft && x <= tabRight) {
            if (x < tabCenter) {
                // 吸附到标签的左侧
                return (draggedIndex < i) ? i - 1 : i;
            } else {
                // 吸附到标签的右侧
                return (draggedIndex < i) ? i : i + 1;
            }
        }
    }
    
    // 如果没有经过任何标签，根据位置决定放在首位或末位
    if (x < tabWidth / 2) {
        return 0; // 放在最左侧
    } else {
        return m_tabs.size() - (draggedTab ? 1 : 0); // 放在最右侧
    }
}

QPoint DockingTabWell::getTabPositionForIndex(int index) const {
    if (index < 0) return QPoint(0, 0);
    
    // 计算累积位置，考虑每个标签的不同宽度；当某个标签正被拖拽时，它不占据固定位置
    int x = 0;
    int logicalIndex = 0;
    for (int i = 0; i < m_tabs.size(); ++i) {
        DockTab* tab = m_tabs[i];
        if (tab == m_draggedTab) {
            // 被拖拽的标签临时不计入排布位置（避免出现空洞）
            continue;
        }
        if (logicalIndex == index) {
            break;
        }
        QSize tabSize = computeAdaptiveTabSize(i);
        x += tabSize.width() - OVERLAP_WIDTH;
        ++logicalIndex;
    }
    
    return QPoint(x, 0);
}

bool DockingTabWell::hasSpaceForNewTab() const {
    // 简单实现：总是有空间（可以滚动或缩小标签）
    return true;
}

// === 布局参数 ===

QSize DockingTabWell::computeTabSize() const {
    return computeAdaptiveTabSize(-1); // 返回当前策略下的基础标签大小
}

QSize DockingTabWell::computeAdaptiveTabSize(int tabIndex) const {
    Q_UNUSED(tabIndex);
    if (m_tabs.isEmpty()) {
        return QSize(MIN_TAB_WIDTH, TAB_HEIGHT);
    }
    
    const int availableWidth = width();
    const int tabCount = m_tabs.size();
    
    // VSCode风格：
    // 1) 若总宽度足以容纳每个标签的最大宽度，则每个标签使用 MAX_TAB_WIDTH，右侧留空，不拉伸填充
    if (tabCount * MAX_TAB_WIDTH <= availableWidth) {
        return QSize(MAX_TAB_WIDTH, TAB_HEIGHT);
    }
    
    // 2) 否则等比分配，并夹在 [MIN, MAX] 区间
    int base = availableWidth / qMax(1, tabCount);
    base = qBound(MIN_TAB_WIDTH, base, MAX_TAB_WIDTH);
    return QSize(base, TAB_HEIGHT);
}

void DockingTabWell::setMaximumTabSize(const QSize& size) {
    if (m_maxTabSize != size) {
        m_maxTabSize = size;
        m_needsLayout = true;
        arrangeChildren();
    }
}

// === 拖拽状态管理 ===

void DockingTabWell::setDraggedTab(DockTab* tab) {
    if (m_draggedTab != tab) {
        m_draggedTab = tab;
        m_needsLayout = true;
        arrangeChildren();
    }
}

void DockingTabWell::clearDraggedTab() {
    if (m_draggedTab) {
        m_draggedTab = nullptr;
        hideDropIndicator();
        m_needsLayout = true;
        arrangeChildren();
    }
}

// === Qt事件重写 ===

void DockingTabWell::paintEvent(QPaintEvent* event) {
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    
    paintBackground(painter);
    paintTabSeparators(painter);
    paintDropIndicator(painter);
    
    QFrame::paintEvent(event);
}

void DockingTabWell::resizeEvent(QResizeEvent* event) {
    QFrame::resizeEvent(event);
    m_needsLayout = true;
    arrangeChildren();
}

void DockingTabWell::mousePressEvent(QMouseEvent* event) {
    if (event->button() == Qt::RightButton) {
        // 右键菜单
        DockTab* clickedTab = findTabAt(event->pos());
        showContextMenu(event->pos(), clickedTab);
        event->accept();
        return;
    }
    
    QFrame::mousePressEvent(event);
}

void DockingTabWell::contextMenuEvent(QContextMenuEvent* event) {
    DockTab* clickedTab = findTabAt(event->pos());
    showContextMenu(event->pos(), clickedTab);
    event->accept();
}

// === 拖放支持 ===

void DockingTabWell::dragEnterEvent(QDragEnterEvent* event) {
    if (event->mimeData()->hasFormat("application/x-docktab")) {
        event->acceptProposedAction();
    } else {
        event->ignore();
    }
}

void DockingTabWell::dragMoveEvent(QDragMoveEvent* event) {
    if (event->mimeData()->hasFormat("application/x-docktab")) {
        // 计算放置位置
        int dropIndex = calculateDropIndexForPosition(event->position().toPoint(), nullptr);
        showDropIndicator(dropIndex);
        event->acceptProposedAction();
    } else {
        event->ignore();
    }
}

void DockingTabWell::dragLeaveEvent(QDragLeaveEvent* event) {
    hideDropIndicator();
    QFrame::dragLeaveEvent(event);
}

void DockingTabWell::dropEvent(QDropEvent* event) {
    if (event->mimeData()->hasFormat("application/x-docktab")) {
        // 获取拖拽的标签
        QByteArray data = event->mimeData()->data("application/x-docktab");
        quintptr tabPtr = data.toULongLong();
        DockTab* droppedTab = reinterpret_cast<DockTab*>(tabPtr);
        
        if (droppedTab) {
            int dropIndex = calculateDropIndexForPosition(event->position().toPoint(), nullptr);
            
            // 如果是从其他TabWell拖来的，添加标签
            if (!m_tabs.contains(droppedTab)) {
                addTab(droppedTab, dropIndex);
            }
            
            event->acceptProposedAction();
        }
    }
    
    hideDropIndicator();
}

// === 尺寸提示 ===

QSize DockingTabWell::sizeHint() const {
    int totalWidth = calculateTotalWidth();
    return QSize(totalWidth, TAB_HEIGHT);
}

QSize DockingTabWell::minimumSizeHint() const {
    // 至少能显示一个标签
    return QSize(MIN_TAB_WIDTH, TAB_HEIGHT);
}

// === DockTab事件处理 ===

void DockingTabWell::onTabActivated() {
    DockTab* tab = qobject_cast<DockTab*>(sender());
    if (tab) {
        bringTabToFront(tab);
    }
}

void DockingTabWell::onTabCloseRequested() {
    DockTab* tab = qobject_cast<DockTab*>(sender());
    if (tab) {
        emit tabCloseRequested(tab);
        removeTab(tab);
        tab->deleteLater();
    }
}

void DockingTabWell::onTabDragStarted() {
    DockTab* tab = qobject_cast<DockTab*>(sender());
    if (tab) {
        setDraggedTab(tab);
        emit tabDragStarted(tab);
    }
}

void DockingTabWell::onTabDragPositionChanged(const QPoint& globalPos) {
    m_lastDragPosition = mapFromGlobal(globalPos);
    updateDragPreview();
}

void DockingTabWell::onTabDragFinished() {
    DockTab* tab = qobject_cast<DockTab*>(sender());
    if (tab) {
        clearDraggedTab();
        emit tabDragFinished(tab, true);
        
        // 确保有有效的前台标签
        ensureValidForegroundTab();
    }
}

void DockingTabWell::onTabHorizontalDragPreview(int fromIndex, int toIndex) {
    m_previewFromIndex = fromIndex;
    m_previewToIndex = toIndex;
    m_showPreview = true;
    
    emit tabDragPreview(fromIndex, toIndex);
    update();
}

void DockingTabWell::onTabHorizontalDragCommit(int fromIndex, int toIndex) {
    // 卡牌式交换：只允许相邻标签交换
    if (fromIndex >= 0 && fromIndex < m_tabs.size() && 
        toIndex >= 0 && toIndex < m_tabs.size() && 
        fromIndex != toIndex &&
        abs(fromIndex - toIndex) == 1) { // 确保是相邻交换
        
        // 交换相邻标签
        m_tabs.swapItemsAt(fromIndex, toIndex);
        
        // 更新前台索引
        if (m_foregroundIndex == fromIndex) {
            m_foregroundIndex = toIndex;
        } else if (m_foregroundIndex == toIndex) {
            m_foregroundIndex = fromIndex;
        } else if (m_foregroundIndex < fromIndex && m_foregroundIndex >= toIndex) {
            m_foregroundIndex++;
        }
        
        // 清理预览状态
        m_showPreview = false;
        m_previewFromIndex = -1;
        m_previewToIndex = -1;
        
        // 更新布局
        m_needsLayout = true;
        arrangeChildren();
        
        DockTab* tab = m_tabs[toIndex];
        emit tabMoved(tab, fromIndex, toIndex);
    }
}

void DockingTabWell::onTabPullOutWindowRequested(const QPoint& globalPos, QWidget* content) {
    DockTab* tab = qobject_cast<DockTab*>(sender());
    if (tab) {
        emit tabPullOutRequested(tab, globalPos);
    }
}

void DockingTabWell::onTabReturnToWell() {
    DockTab* tab = qobject_cast<DockTab*>(sender());
    if (tab && m_tabs.contains(tab)) {
        // 重新显示该标签的内容
        bringTabToFront(tab);
    }
}

// === 布局管理 ===

void DockingTabWell::arrangeChildren() {
    if (!m_needsLayout || m_tabs.isEmpty()) return;
    
    updateTabPositions();
    m_needsLayout = false;
}

void DockingTabWell::updateTabPositions() {
    for (int i = 0; i < m_tabs.size(); ++i) {
        DockTab* tab = m_tabs[i];
        if (tab == m_draggedTab) continue; // 跳过被拖拽的标签
        
        QRect geometry = calculateAdaptiveTabGeometry(i);
        tab->setGeometry(geometry);
        tab->setOriginalPosition(geometry.topLeft());
        
        // 确保标签可见
        tab->show();
        tab->raise();
    }
    
    // 前台标签置顶
    if (foregroundTab() && foregroundTab() != m_draggedTab) {
        foregroundTab()->raise();
    }
}

QRect DockingTabWell::calculateAdaptiveTabGeometry(int index) const {
    if (index < 0 || index >= m_tabs.size()) {
        return QRect();
    }
    
    // 使用自适应大小
    QSize tabSize = computeAdaptiveTabSize(index);
    QPoint position = getTabPositionForIndex(index);
    
    return QRect(position, tabSize);
}

QRect DockingTabWell::calculateTabGeometry(int index, bool isDragged) const {
    if (index < 0 || index >= m_tabs.size()) {
        return QRect();
    }
    
    QSize tabSize = computeTabSize();
    int tabWidth = tabSize.width() - OVERLAP_WIDTH;
    
    // 计算X位置
    int x = index * tabWidth;
    
    // 如果有拖拽的标签，需要为其预留空间
    if (m_draggedTab && !isDragged) {
        int draggedIndex = getTabIndex(m_draggedTab);
        if (draggedIndex >= 0 && index > draggedIndex) {
            // 为拖拽标签预留空间
            x += tabWidth;
        }
    }
    
    return QRect(x, 0, tabSize.width(), tabSize.height());
}

int DockingTabWell::calculateTotalWidth() const {
    if (m_tabs.isEmpty()) return 0;
    
    // 总宽度为当前策略下单个标签宽乘以数量
    int w = computeAdaptiveTabSize(0).width();
    return w * m_tabs.size();
}

// === 拖拽辅助 ===

void DockingTabWell::showDropIndicator(int index) {
    if (m_dropIndicatorIndex != index) {
        m_dropIndicatorIndex = index;
        update();
    }
}

void DockingTabWell::hideDropIndicator() {
    if (m_dropIndicatorIndex != -1) {
        m_dropIndicatorIndex = -1;
        update();
    }
}

void DockingTabWell::updateDragPreview() {
    if (m_draggedTab && !m_lastDragPosition.isNull()) {
        int newDropIndex = calculateDropIndexForPosition(m_lastDragPosition, m_draggedTab);
        showDropIndicator(newDropIndex);
    }
}

// === 绘制辅助 ===

void DockingTabWell::paintBackground(QPainter& painter) {
    // 背景由样式表处理
}

void DockingTabWell::paintDropIndicator(QPainter& painter) {
    if (m_dropIndicatorIndex < 0) return;
    
    QPoint indicatorPos = getTabPositionForIndex(m_dropIndicatorIndex);
    
    // 绘制放置指示线
    painter.setPen(QPen(QColor(0, 120, 215), DROP_INDICATOR_WIDTH));
    painter.drawLine(indicatorPos.x(), 0, indicatorPos.x(), height());
    
    // 绘制箭头
    QPolygon arrow;
    int arrowSize = 6;
    arrow << QPoint(indicatorPos.x() - arrowSize, arrowSize);
    arrow << QPoint(indicatorPos.x(), 0);
    arrow << QPoint(indicatorPos.x() + arrowSize, arrowSize);
    
    painter.setBrush(QColor(0, 120, 215));
    painter.drawPolygon(arrow);
}

void DockingTabWell::paintTabSeparators(QPainter& painter) {
    if (m_tabs.size() < 2) return;
    
    // 使用低对比度的细分隔线，增强边界感而不产生“裂谷”
    painter.setPen(QPen(QColor(46, 46, 46), 1)); // #2e2e2e
    
    for (int i = 0; i < m_tabs.size() - 1; ++i) {
        // 在标签边界处绘制分隔线
        QPoint pos = getTabPositionForIndex(i + 1);
        int x = pos.x();
        painter.drawLine(x, 4, x, height() - 4);
    }
}

// === 标签页连接管理 ===

void DockingTabWell::connectTabSignals(DockTab* tab) {
    if (!tab) return;
    
    connect(tab, &DockTab::tabActivated, this, &DockingTabWell::onTabActivated);
    connect(tab, &DockTab::tabCloseRequested, this, &DockingTabWell::onTabCloseRequested);
    connect(tab, &DockTab::dragStarted, this, &DockingTabWell::onTabDragStarted);
    connect(tab, &DockTab::dragPositionChanged, this, &DockingTabWell::onTabDragPositionChanged);
    connect(tab, &DockTab::dragFinished, this, &DockingTabWell::onTabDragFinished);
    connect(tab, &DockTab::horizontalDragPreview, this, &DockingTabWell::onTabHorizontalDragPreview);
    connect(tab, &DockTab::horizontalDragCommit, this, &DockingTabWell::onTabHorizontalDragCommit);
    connect(tab, &DockTab::pullOutWindowRequested, this, &DockingTabWell::onTabPullOutWindowRequested);
    connect(tab, &DockTab::returnToTabWell, this, &DockingTabWell::onTabReturnToWell);
}

void DockingTabWell::disconnectTabSignals(DockTab* tab) {
    if (!tab) return;
    
    disconnect(tab, nullptr, this, nullptr);
}

// === 工具函数 ===

DockTab* DockingTabWell::findTabAt(const QPoint& pos) const {
    for (DockTab* tab : m_tabs) {
        if (tab->geometry().contains(pos)) {
            return tab;
        }
    }
    return nullptr;
}

void DockingTabWell::ensureValidForegroundTab() {
    if (m_tabs.isEmpty()) {
        m_foregroundIndex = -1;
        return;
    }
    
    if (m_foregroundIndex < 0 || m_foregroundIndex >= m_tabs.size()) {
        // 激活最右边的标签（按照需求）
        bringTabToFront(m_tabs.size() - 1);
    }
}

void DockingTabWell::updateTabStyles() {
    for (DockTab* tab : m_tabs) {
        // 标签自己会处理样式更新
        tab->update();
    }
}

// === 右键菜单 ===

void DockingTabWell::showContextMenu(const QPoint& pos, DockTab* clickedTab) {
    QMenu menu(this);
    
    if (clickedTab) {
        menu.addAction(tr("激活标签页"), [this, clickedTab]() {
            bringTabToFront(clickedTab);
        });
        
        if (clickedTab->isClosable()) {
            menu.addAction(tr("关闭标签页"), [this, clickedTab]() {
                removeTab(clickedTab);
                clickedTab->deleteLater();
            });
            
            menu.addAction(tr("关闭其他标签页"), [this, clickedTab]() {
                for (int i = m_tabs.size() - 1; i >= 0; --i) {
                    DockTab* tab = m_tabs[i];
                    if (tab != clickedTab && tab->isClosable()) {
                        removeTab(tab);
                        tab->deleteLater();
                    }
                }
            });
        }
        
        menu.addSeparator();
    }
    
    menu.addAction(tr("新建标签页"), [this]() {
        // 发送信号让上层处理
        // emit newTabRequested();
    });
    
    menu.exec(mapToGlobal(pos));
}

// === 主标签管理实现 ===

DockTab* DockingTabWell::mainTab() const {
    for (DockTab* tab : m_tabs) {
        if (tab->tabType() == DockTab::TabType::MainTab) {
            return tab;
        }
    }
    return nullptr;
}

int DockingTabWell::mainTabIndex() const {
    for (int i = 0; i < m_tabs.size(); ++i) {
        if (m_tabs[i]->tabType() == DockTab::TabType::MainTab) {
            return i;
        }
    }
    return -1;
}

bool DockingTabWell::hasMainTab() const {
    return mainTab() != nullptr;
}

void DockingTabWell::setMainTab(DockTab* tab) {
    if (!tab || !m_tabs.contains(tab)) return;
    
    // 将指定标签设置为主标签类型
    tab->setTabType(DockTab::TabType::MainTab);
    
    // 确保只有一个主标签，将其他主标签改为普通标签
    for (DockTab* otherTab : m_tabs) {
        if (otherTab != tab && otherTab->tabType() == DockTab::TabType::MainTab) {
            otherTab->setTabType(DockTab::TabType::NormalTab);
        }
    }
}
